const superagent = require("superagent");
const Request = require("request");
const fse = require("fs-extra");
const path = require("path");
const download = require("download");

let defaultOption = {
	Accept: "*/*",
	"Accept-Encoding": "gzip, deflate, br",
	"Cache-Control": "no-cache",
	Connection: "keep-alive",
	"Content-Type": "application/json; charset=UTF-8"
};

const requestGet = ({ url, option = {}, param = {} }) => {
	Object.assign(option, defaultOption);
	return new Promise((resolve, reject) => {
		superagent
			.get(url)
			.query(param)
			.set(option)
			.end((err, res) => {
				if (err) {
					resolve(err || "req error");
				}
				if (res.ok) {
					if (res.type.includes("image")) {
						resolve({
							type: res.type,
							data: res.body
						});
					} else {
						resolve(option.string ? res.text : JSON.parse(res.text));
					}
				} else {
					resolve(err || "req error");
				}
			});
	});
};

const requestPost = ({ url, option = {}, param = {}, data }) => {
	Object.assign(defaultOption, option);
	return new Promise((resolve, reject) => {
		superagent
			.post(url)
			.query(param)
			.set(defaultOption)
			.send(data)
			.end((err, res) => {
				if (res.ok) {
					try {
						resolve(
							option.string ? res.text : JSON.parse(res.text)
						);
					} catch (err) {
						resolve(err || "req error");
					}
				} else {
					resolve(err || "req error");
				}
			});
	});
};

exports.request = ({
	method = "GET",
	url,
	option = {},
	param = {},
	data = {}
}) => {
	if (!url) {
		return Promise.reject("url is must param");
	}
	if (method === "GET") {
		return requestGet({ url, option, param });
	} else if (method === "POST") {
		return requestPost({ url, option, param, data });
	}
};

/**
 *
 * @param {Object} param
 * @description
 * m message
 * d data
 * s status
 * e extra
 * @returns Object
 */
exports.result = (param = {}) => {
	let msg = param.m;
	if (msg) {
		param.m = typeof msg === "object" ? JSON.stringify(msg) : msg;
	}

	let defaultParam = {
		m: "success",
		d: "",
		s: 1,
		e: {}
	};
	return Object.assign(defaultParam, param);
};

exports.compileHtml = arr => {
	let str = "";

	return jsonToHtml(arr);

	function jsonToHtml(data) {
		const SINGLELABEL = ["img", "br", "hr"];
		if (data === undefined) {
			return "";
		}
		//判断是否有children节点
		if (!Array.isArray(data)) {
			return "";
		}
		//判断是否有children的长度为o 直接返回
		if (data.length <= 0) {
			return "";
		}
		str = data.map(function(element) {
			let attrStr = "";
			//如果拥有属性就循环属性
			if (typeof element.attrs === "object") {
				for (var key in element.attrs) {
					attrStr += `${key}="${element.attrs[key]}"  `;
				}
			}
			//判断是否为Text 一类 没有name
			if (element.type) {
				return `<span ${attrStr}>${element.text}</span>`;
				return `<${element.type} ${attrStr}>${element.text}</${
					element.type
				}>`;
			}
			//节点返回

			//如果单标签暂时不判断
			if (SINGLELABEL.includes(element.name)) {
				return `<${element.name} ${attrStr}>${jsonToHtml(
					element.children
				)}</${element.name}>`;
			} else {
			}

			return `<${
				element.name
			} ${attrStr}>${jsonToHtml(element.children)}</${element.name}>`;
		});
		//如果拥有多个兄弟节点就拼接在一起
		if (Array.isArray(str)) {
			str = str.join("");
		}
		return str;
	}
};

exports.getStatic = ({ url = "", filePath = null }) => {
	let fileType = path.extname(url) || ".jpg";
	fileType = fileType.replace(/\?.+/, "");
	return new Promise((resolve, reject) => {
		try {
			if (filePath) {
				let fileWritePath = filePath + fileType;
				download(url)
					.then(data => {
						fse.writeFileSync(fileWritePath, data);
						resolve();
					})
					.catch(err => {
						reject(err);
					});
			} else {
				Request(
					{
						url,
						encoding: null
					},
					function(error, response, body) {
						if (error) {
							reject(err);
						}

						resolve({
							body,
							type: response.headers["content-type"]
						});
					}
				);
			}
		} catch (error) {
			reject(error);
		}
	});
};

exports.serializeStr = async (data = [], isReplaceImage = false) => {
	let str = "";
	for (let i = 0, dataLen = data.length; i < dataLen; i++) {
		let item = data[i];
		if (isReplaceImage) {
			try {
				item.url = await replaceImage(item.url);
			} catch (error) {}
		}

		if (item.url) {
			str += `<p style='text-align:center;'><img style='width: 100%;padding-bottom: 10px;padding-top: 10px;' src='${
				isReplaceImage ? "" : "//collect.zmwxxcx.com/proxy/img?u="
			}${item.url}'></p>`;
		}

		if (item.text) {
			str += `<p style='text-align: center;font-size: 20px;padding: 10px;letter-spacing: 1px;line-height: 30px;'>${
				item.text
			}</p>`;
		}
	}

	return `${str}`;
};

exports.hashConcatUrl = (hash, useSpace) =>
	`https://${useSpace}.zmwxxcx.com/${hash}`;
